package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理支付超时订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder(){
        log.info("处理支付超时订单：{}", new Date());
    //     获取到所有超时订单
    //     获取到当前时间 - 15分钟
        LocalDateTime time = LocalDateTime.now().minusMinutes(10);
        List<Orders> orders = orderMapper.getTimeoutOrders(time, Orders.PENDING_PAYMENT);
        if (!orders.isEmpty()) {
            orders.forEach(order -> {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason(MessageConstant.ORDER_TIMEOUT);
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            });
        }
    }

    /**
     * 处理“派送中”状态的订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processDeliveryOrder(){
        log.info("处理派送中订单：{}", new Date());
        LocalDateTime time = LocalDateTime.now().minusSeconds(15);
        List<Orders> orders = orderMapper.getTimeoutOrders(time, Orders.DELIVERY_IN_PROGRESS);
        if (!orders.isEmpty()) {
            orders.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
                order.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(order);
            });
        }
    }

    /**
     * 处理待接单订单
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processNotConfirmOrder(){
        log.info("处理待接单订单：{}", new Date());
        LocalDateTime time = LocalDateTime.now().minusMinutes(13);
        List<Orders> orders = orderMapper.getTimeoutOrders(time, Orders.TO_BE_CONFIRMED);
        if (!orders.isEmpty()) {
            orders.forEach(order -> {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason(MessageConstant.ORDER_TIMEOUT);
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            });
        }
    }

}